package com.fuyu.common.model;

import com.fuyu.common.enums.ResultCodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;

import java.io.Serializable;

/**
 * 统一响应结构体
 *
 * @author haoxr
 * @since 2022/1/30
 **/
@Tag(name = "统一响应结构体")
@Data
public class R<T> implements Serializable {

    @Schema(description = "状态码")
    private Integer code;

    @Schema(description = "响应信息")
    private String msg;

    @Schema(description = "响应数据")
    private T data;


    /**
     * 构建响应
     *
     * @param code 响应状态码
     * @param msg  响应信息
     */
    private static <T> R<T> build(Integer code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(null);
        r.setMsg(msg);
        return r;
    }


    /**
     * 获取枚举信息
     *
     * @param resultCodeEnum 响应状态码枚举
     */
    private static <T> R<T> getEnumInfo(ResultCodeEnum resultCodeEnum) {
        return build(resultCodeEnum.getCode(), resultCodeEnum.getMsg());
    }

    /**
     * 成功响应
     *
     * @param data 响应数据
     */
    public static <T> R<T> success(T data) {
        R<T> r = getEnumInfo(ResultCodeEnum.SUCCESS);
        r.setData(data);
        return r;
    }


    /**
     * 成功响应
     *
     * @param msg 提示信息
     */
    public static <T> R<T> success(String msg) {
        R<T> r = getEnumInfo(ResultCodeEnum.SUCCESS);
        r.setMsg(msg);
        return r;
    }

    /**
     * 失败响应
     */
    public static <T> R<T> failed() {
        return getEnumInfo(ResultCodeEnum.FAILED);
    }

    /**
     * 失败响应
     *
     * @param msg 提示信息
     */
    public static <T> R<T> failed(String msg) {
        R<T> r = getEnumInfo(ResultCodeEnum.FAILED);
        r.setMsg(msg);
        return r;
    }

    public static <T> R<T> failed(Integer code, String msg) {
        R<T> r = build(code, msg);
        return r;
    }


    public static <T> R<T> crud(Integer row) {
        if (row > 0) {
            R<T> ok = success("成功");
            ok.setCode(2000);
            return ok;
        }

        R<T> failed = failed("失败");
        failed.setCode(4000);
        return failed;
    }

    public static <T> R<T> crud(boolean result) {
        if (result) {
            R<T> ok = success("成功");
            ok.setCode(2000);
            return ok;
        }
        R<T> failed = failed("失败");
        failed.setCode(4000);
        return failed;
    }

}
